import { ref, Ref } from "vue";
import { Role } from "@/models/dataPeople/Role";
import api from "@/utils";
import { AxiosResponse } from "axios";
import { UserRoleRelation } from "@/models/system/UserRoleRelation";
import { ElMessage } from "element-plus";
import Scope from "@/models/Scope";

export function UserManage() {
  const allRoleList: Ref<Role[]> = ref([]);
  const roleTreeRef = ref();
  const currentUserId = ref();
  const roleTreeProps = {
    children: "children",
    label: "name",
  };
  const getAllRoleList = () => {
    api.http
      .postJson("/basic-request/role/search", {})
      .then((res: AxiosResponse) => {
        allRoleList.value = res.data;
      });
  };

  // 设置当前点击的用户
  const currentUserIdAuthorization = (scoped: Scope) => {
    currentUserId.value = scoped.row.id;
    api.http
      .get("/system/selectRoleIdByUserId/" + scoped.row.id)
      .then((res: AxiosResponse) => {
        roleTreeRef.value.setCheckedKeys(res.data);
      });
  };

  const submitSetRole = () => {
    const userRoleRelation = [] as UserRoleRelation[];
    roleTreeRef.value.getCheckedKeys().forEach((item: number) => {
      userRoleRelation.push({
        userId: currentUserId.value,
        roleId: item,
        createUser: sessionStorage.getItem("token") as string,
        createGmt: new Date(),
      });
    });
    api.http
      .postJson("/system/setUserRoleRelation", userRoleRelation)
      .then(() => {
        ElMessage.success("设置成功!");
      })
      .catch(() => {
        ElMessage.error("设置失败!");
      });
  };
  return {
    allRoleList,
    roleTreeRef,
    roleTreeProps,
    getAllRoleList,
    submitSetRole,
    currentUserIdAuthorization,
  };
}
